package org.diysearch.dao.impls;

import java.sql.SQLException;
import java.util.List;

import org.diysearch.dao.interfaces.CategoryDao;
import org.diysearch.models.Category;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

public class CategoryDaoImpl extends SqlMapClientDaoSupport implements
		CategoryDao {

	@Override
	public int delete(Category c) throws SQLException {
		return getSqlMapClientTemplate().delete("delete-category",c);
	}

	@Override
	public int delete(List<Category> categories) throws SQLException {
		int code = 0;
		for (Category c : categories) {
			code += delete(c);
		}
		return code;
	}

	@Override
	public Category findById(int id) throws SQLException {
		Category c = new Category();
		c.setId(id);
		return (Category) getSqlMapClientTemplate().queryForObject("findById-category",c);
	}

	@Override
	public List<Category> findByParent(int parentId) throws SQLException {
		Category c = new Category();
		c.setParentId(parentId);
		return getSqlMapClientTemplate().queryForList("findByParent-category",c);
	}

	@Override
	public int save(Category c) throws SQLException {
		int code = 0;
		if (c.getId() > 0) {
			Category _c = (Category) getSqlMapClientTemplate().insert("insert-category",c);
			code = _c.getId();
		} else {
			code = getSqlMapClientTemplate().update("update-category",c);
		}
		return code;
	}
	
	@Override
	public int save(List<Category> categories) throws SQLException {
		int code = 0;
		for (Category c : categories) {
			code += save(c);
		}
		return code;
	}

	@Override
	public Category findByName(String name) throws SQLException {
		Category c = new Category();
		c.setName(name);
		return (Category) getSqlMapClientTemplate().queryForObject("findByName-category",c);
	}

}
